#include <stdio.h>
#include <cstring>
#include <unistd.h>
#include <iostream>
#include <sys/types.h>
  #include <sys/wait.h>

void ChildWrite(int wfd)
{
    int cnt=10;
    while(cnt--)
    {
        sleep(1);
char buf[1024]={0};
snprintf(buf,sizeof(buf),"我是子进程,我的cnt现在的值是:%d",cnt);
write(wfd,buf,strlen(buf));
    }

}

void FatherRead(int rfd)
{
while(true)
{
    char buff[1024]={0};
    int n=read(rfd,buff,sizeof(buff));
    if(n>0)
    std::cout<<buff<<std::endl;
    else if(n<0)
    continue;
    else 
    {
        printf("写段已经关闭了,那我也退出吧\n");
        exit(0);
    }
}
}

int main()
{
    // 创建管道文件吧
    int fds[2] = {0};
    int n = pipe(fds);
    if (n < 0)
    {
        perror("pipe fail");
        return -1;
    }
    // 管道文件创建成功
    pid_t id = fork();
    //f->r,c->w
    if(id==0)
    {
        //子进程
        close(fds[0]);
        ChildWrite(fds[1]);
        close(fds[1]);
        exit(0);

    }else {
        close(fds[1]);
        FatherRead(fds[0]);
        close(fds[0]);
        waitpid(id,nullptr,0);

    }

    std::cout << "fds[0]=" << fds[0] << std::endl;
    std::cout << "fds[1]=" << fds[1] << std::endl;
    return 0;
}